import React, { useMemo } from 'react';
import { useDataStream } from './hooks/useDataStream';
import { Header } from './components/Header';
import { Sidebar } from './components/Sidebar';
import { SystemStatusPanel } from './components/SystemStatusPanel';
import { DataVisualization } from './components/DataVisualization';

const App: React.FC = () => {
  const {
    isRunning,
    servers,
    tasks,
    alerts,
    systemStatus,
    toggleDataStream,
    refreshData,
    searchTerm,
    setSearchTerm
  } = useDataStream();

  const filteredTasks = useMemo(() => {
    if (!searchTerm) return tasks;
    return tasks.filter(task =>
      task.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      task.targetCluster.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [tasks, searchTerm]);

  const recentAlerts = useMemo(() => {
    return alerts
      .filter(alert => !alert.resolved)
      .sort((a, b) => b.timestamp - a.timestamp)
      .slice(0, 10);
  }, [alerts]);

  return (
    <div className="flex flex-col h-screen bg-primary-bg">
      <Header
        isRunning={isRunning}
        onToggleStream={toggleDataStream}
        onRefresh={refreshData}
        searchTerm={searchTerm}
        onSearchChange={setSearchTerm}
      />

      <div className="flex flex-1 overflow-hidden">
        <Sidebar
          tasks={filteredTasks}
          alerts={recentAlerts}
          searchTerm={searchTerm}
        />

        <div className="flex-1 flex flex-col p-4 gap-4 min-w-0">
          <div className="h-[35%] min-h-[250px] max-h-[450px]">
            <SystemStatusPanel systemStatus={systemStatus} />
          </div>

          <div className="flex-1 min-h-0">
            <DataVisualization servers={servers} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;